<?php

namespace app\models;

use Yii;
use yii\base\Model;
use yii\web\UploadedFile;
use yii\web\HttpException;
use Qiniu;
use Qiniu\Auth ;

use helper\QiniuHelper; 



/**
* UploadForm is the model behind the upload form.
*/
class UploadForm extends Model
{   


    /**
    * @var UploadedFile file attribute
    */
    public $image_file;

    /**
    * @return array the validation rules.
    */
    public function rules()
    {
        return [
            [['image_file'], 'file'],
        ];
    }

    public function upload()
    {
        $bpath =  dirname(Yii::$app->BasePath).'/bkshop_admin/uploads/';
        if(!file_exists($bpath))mkdir($bpath);  
        $uid = $this->guid();
        $filePath = $bpath . $uid . '.' . $this->image_file->extension ; 
        
        if ($this->validate()) {
            $this->image_file->saveAs($filePath);
            return QiniuHelper::uploadQiniu($filePath,$uid . '.' . $this->image_file->extension);
        } else {
            return false;
        }
    }


    

    function guid(){
        if (function_exists('com_create_guid')){
            return com_create_guid();
        }else{
            mt_srand((double)microtime()*10000);//optional for php 4.2.0 and up.
            $charid = strtoupper(md5(uniqid(rand(), true)));
            $hyphen = chr(45);// "-"
            $uuid = //chr(123)// "{"
                    substr($charid, 0, 8).$hyphen
                    .substr($charid, 8, 4).$hyphen
                    .substr($charid,12, 4).$hyphen
                    .substr($charid,16, 4).$hyphen
                    .substr($charid,20,12)
                    ;//chr(125);// "}"
            return $uuid;
        }
    }
}